package com.cdxy.util;

/**
 * @Author: tangy
 * @Date: 2020/3/7 17:50
 */
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JwtUtil {
    private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);

    public JwtUtil() {
    }

    public static String genToken(Map<String, String> claims, String privateKey) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, JWTCreationException {
        Algorithm algorithm = null;
        algorithm = Algorithm.RSA256((RSAPublicKey)null, (RSAPrivateKey) AlgorithmUtil.Rsa.getPrivateKey(privateKey));
        Builder builder = JWT.create().withIssuedAt(new Date());
        claims.forEach(builder::withClaim);
        return builder.sign(algorithm);
    }

    public static Map<String, String> verifyToken(String token, String publicKey) throws IOException, JWTVerificationException, InvalidKeySpecException, NoSuchAlgorithmException {
        Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) AlgorithmUtil.Rsa.getPublicKey(publicKey), (RSAPrivateKey)null);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = null;
        jwt = verifier.verify(token);
        Map<String, Claim> map = jwt.getClaims();
        Map<String, String> resultMap = Maps.newHashMap();
        map.forEach((k, v) -> {
            String var10000 = (String)resultMap.put(k, v.asString());
        });
        if (jwt.getIssuedAt() != null) {
            resultMap.put("iat", String.valueOf(jwt.getIssuedAt().getTime() / 1000L));
        }

        return resultMap;
    }
}

